<?php
/**
 * Create By: PhpStorm
 * User: yihua
 * File: AddUserCoupon.php
 * Date: 2017/1/6
 * Time: 2:18
 */

namespace app\api\model\page\user;

use app\library\PageBase;
use app\api\model\dao\UserCoupon;
use app\api\model\dao\Coupon;
use think\Log;
use app\library\Error;
use think\Db;
use think\Exception;

class AddUserCoupon extends PageBase
{
    private $objUserCouponModel;

    public function __construct()
    {
        parent::__construct();
        $this->objUserCouponModel = new UserCoupon();
    }

    public function excute($param)
    {
        $ret = $this->checkToken($param);
        if (false === $ret) {
            return $this->getRes(Error::ERR_NO_AUTH);
        }

        if (empty($param['coupon_id'])) {
            return $this->getRes(Error::ERR_PARAM, '请选择优惠券');
        }

        $objUserCoupon = new UserCoupon();
        //判断是否已经领取了同类型的优惠券
        $ret = $objUserCoupon->getCouponByUserid($this->user_id);
        foreach ($ret as $value) {
            if ($value['coupon_id'] == $param['coupon_id']) {
                //return $this->getRes(Error::ERR_COUPON_RECEIVED);
            }
        }
        //return $ret;
        // 启动事务
        Db::startTrans();
        try {
            $objCoupon = new Coupon();
            //判断coupon_id存在
            $couponInfo = $objCoupon->getCouponById($param['coupon_id']);
            if (false === $couponInfo) {
                throw new Exception(Error::ERR_SYS);
            }
            if (empty($couponInfo)) {
                throw new Exception(Error::ERR_COUPON_NOT_EXISTS);
            }
            //判断coupon_id是否使用已经领完
            if ($couponInfo['amount_remained'] == '0') {
                throw new Exception(Error::ERR_COUPON_OUT_OF_RANGE);
            }

            //将coupon_id剩余数量减小
            try {
                $objCoupon->decreaseRemained($param['coupon_id']);
            } catch (\Exception $e) {
                Log::alert('decreaseRemained failed');
                throw new Exception(Error::ERR_SYS);
            }

            //user_coupon增加一条
            $content = [
                'coupon_name' => $couponInfo['coupon_name'],
                'price' => $couponInfo['price'],
                'base_price' => $couponInfo['base_price'],
                'type' => $couponInfo['type'],
                'description' => $couponInfo['description'],
                'start_time' => $couponInfo['start_time'],
                'end_time' => $couponInfo['end_time'],
            ];
            $ret = $objUserCoupon->addCoupon($this->user_id, $param['coupon_id'], $content);
            if (false === $ret) {
                Log::alert('addCoupon failed');
                throw new Exception(Error::ERR_SYS);
            }

            Db::commit();
            return $this->getRes();
        } catch (Exception $e) {
            Db::rollback();
            return $this->getRes($e->getMessage());
        }
    }
}
